//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by 谭仁川 on 15/11/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    
    var account: UserAccount?
    
    override init() {
        super.init()
        account = UserAccount.loadAccount()
    }
    
    //用户是否登录
    var userLogin: Bool {
        return account?.access_token != nil
    }
    
    var token: String? {
        return account?.access_token
    }
    
    //用户名的计算性属性
    
    var userName: String? {
        return account?.name
    }
    
    //用户头像 url
    var headImageURL: NSURL? {
        let url = NSURL(string: account?.avatar_large ?? "")
        return url
    }
    
    //请求用户的token
    func loadAccessToken(code: String,finished: (error: NSError? ) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求的参数需要拼装成字典格式
        let paramters = ["client_id": client_id, "client_secret" : client_secret,"grant_type":"authorization_code","code":code, "redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        //添加反序列化类型
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: paramters, success: { (_, result) -> Void in
            //拿到用户token之后 立即请求用户信息
            guard let dict = result as? [String: AnyObject] else {
                return
            }
            
            let account = UserAccount(dict: dict)
            
            //加载用户信息
            self.loadUserInfo(account, finished: finished)
            }) { (_, error) -> Void in
                finished(error: error)
                print(error)
        }
    }
    
    
    private func loadUserInfo(account: UserAccount,finished: (error: NSError? ) -> ()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        //为了保险起见 判断一下
        guard let access_token = account.access_token,userId = account.uid else {
            //            SVProgressHUD.showErrorWithStatus("获取网络数据失败,请稍后再试")
            return
        }
        let parameters = ["access_token": access_token, "uid": userId]
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            //            print(result)
            //转换数据类型的时候  as + ? 还是 ! 需要根据接受的数据类型是什么类型 来添加
            account.avatar_large = result["avatar_large"] as? String
            account.name = result["name"] as? String
            //保存用户信息
            account.saveAccount()
            finished(error: nil)
            }) { (_, error) -> Void in
                finished(error: error)
                print(error)
        }
    }
}
